package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.pojo.*;
import com.itheima.service.AdminService;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;

    //1.注册管理员 /admin/add
    @RequestMapping("/add")
    public Result add(@RequestBody AdminVO adminVO,HttpServletRequest request) {

        //1 查询用户注册的用户名是否存，存在则返回错误提示，该用户名已存在
        Admin admin = adminService.findAdmin1ByName(adminVO.getUserName());
        if (admin!=null){
            return new Result(StatusCode.ERROR,"该用户名已存在");
        }
        try {
            int i = adminService.add(adminVO,request);
            if(i>0){
                return new Result(StatusCode.OK,"注册成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(StatusCode.ERROR,"注册失败");
    }

    //2.分配用户角色信息列表 POST /admin/assign  (adminUid  管理员uid)
    @RequestMapping("/assign")
    public Result assign(HttpServletRequest request) {

        Map<String, Object> userInfo = TokenUtil.getUserInfo(request);
        String adminUid = (String) userInfo.get("uid");
        try {
            //查询封装数据，返回结果
           Map map=adminService.assign(adminUid);
            return new Result(StatusCode.OK,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"分配失败");
        }
    }

    //3.删除部分管理员信息  POST /admin/delete  (Array[string] adminUids)
    @RequestMapping("/delete")
    public Result delete(String[] adminUids  ) {
        //用户删除post请求，字符串数据接收
        System.out.println(adminUids[0]+"==============s");
        String adminUid = adminUids[0];

        System.out.println(adminUid+":====adminUidS");
        try{
            int i = adminService.delete(adminUid);
            if (i>0){
                return  new Result(StatusCode.OK,"删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new Result(StatusCode.OK,"删除失败");
    }


    //4.更新管理员基本信息  POST /admin/edit
    @RequestMapping("/edit")
    public Result edit(@RequestBody AdminVO adminVO,HttpServletRequest request) {

        try {
            int i = adminService.edit(adminVO,request);
            if (i>0){
                return  new Result(StatusCode.OK,"更新成功");
            }
        } catch (Exception e) {
             e.printStackTrace();
        }
        return  new Result(StatusCode.ERROR,"更新失败");
    }

    //5.强退用户  /admin/forceLogout (Array[string] tokenList)
    @RequestMapping("/forceLogout")
    public Result forceLogout(HttpServletRequest request) {
        //删除token
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("Authorization".equals(name)){
                CookieUtils.deleteCookie(name);
            }
        }
        //用户退出， 删除token
        return new Result(StatusCode.OK,"退出成功");
    }


    //6.获取管理员列表  GET /admin/getList   (keyword,currentPage ,pageSize)
    @RequestMapping("/getList")
    public Map getList(String keyword,Integer currentPage,Integer pageSize) throws Exception {
        System.out.println(keyword+currentPage+pageSize+"====================");
        PageInfo<Admin> page=  adminService.getList(keyword,currentPage,pageSize);
        System.out.println(page+"pageInfo=============");

        List<Admin> adminList= page.getList();
        long total = page.getTotal();

        Map<String, Object> map5 = new HashMap<>();

        //封装查询到的数据
        List<Map<String,Object>> list=new ArrayList<>();

        for (Admin admin :adminList) {

            Map<String, Object> map1 = new HashMap<>();

            map1.put("userName",admin.getUserName());
            map1.put("roleUid",admin.getRoleUid());
            map1.put("passWord",admin.getPassWord());
            map1.put("nickName",admin.getNickName());
            map1.put("gender",admin.getGender());

            map1.put("avatar",admin.getAvatar());
            map1.put("email",admin.getEmail());

            map1.put("birthday",admin.getAvatar());
            map1.put("mobile",admin.getEmail());
            map1.put("qqNumber",admin.getEmail());
            map1.put("weChat",admin.getEmail());
            map1.put("occupation",admin.getEmail());
            map1.put("summary",admin.getEmail());
            map1.put("personResume",admin.getEmail());

            map1.put("loginCount",admin.getLoginCount());
            map1.put("lastLoginTime",DateUtils.parseDate2String(admin.getLastLoginTime()));
            map1.put("lastLoginIp",admin.getLastLoginIp());
            map1.put("github",admin.getLastLoginIp());
            map1.put("gitee",admin.getLastLoginIp());

            map1.put("photoList",admin.getPhotoList());

            Role role = admin.getRole();
            Map<String, Object> map4 = new HashMap<>();

            //封装角色数据
            map4.put("roleName",role.getRoleName());
            System.out.println(role.getRoleName()+"角色名称==================");
            map4.put("summary",role.getSummary());
            map4.put("categoryMenuUids",role.getCategoryMenuUids());
            map4.put("uid",role.getUid());
            map4.put("status",role.getStatus());
            map4.put("createTime",DateUtils.parseDate2String(role.getCreateTime()));
            map4.put("updateTime",DateUtils.parseDate2String(role.getUpdateTime()));
            map1.put("role",map4);

            //封装admin数据
            map1.put("uid",admin.getUid());
            map1.put("status",admin.getStatus());
            map1.put("createTime",admin.getCreateTime());
            map1.put("updateTime",admin.getUpdateTime());
            list.add(map1);
        }

        map5.put("records",list );
        map5.put("total", total);
        map5.put("size",  currentPage);
        map5.put("current", pageSize);

        ArrayList<Object> list2 = new ArrayList<>();
        map5.put("orders", list2);
        map5.put("optimizeCountSql", true);
        map5.put("isSearchCount", true);

        Map<String, Object> result = new HashMap<>();
        //返回结果
        result.put("code", "success");
        result.put("data", map5);
        return result;
    }


    //7.获取在线管理员列表  GET /admin/getOnlineAdminList (keyword,currentPage ,pageSize)
    //{"code":"success","data":[{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjI4MzQ2ODgsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NjQzNCwibmJmIjoxNTk2NzYyODM0fQ.a_P4bDRQELWfec_8r5ZvzXgQ9y6m9XqzgF1R2PyqVsQ","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.112","loginLocation":"内网IP|内网IP","browser":"Chrome-83.0.4103.97","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:13:54"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjM0NDg4MzMsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NzA0OCwibmJmIjoxNTk2NzYzNDQ4fQ.AYjh6fkPT1OuOUjnFLCydJaoHe4yaXNLb4wZ0kuMQUs","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.95","loginLocation":"内网IP|内网IP","browser":"Chrome-84.0.4147.105","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:24:08"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjI2NTIzNTMsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5NzAyMTg1MiwibmJmIjoxNTk2NzYyNjUyfQ.86u5ZI71wngoN-GotlWKsbFJ0frmrOXszWUl_CQvf70","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.90","loginLocation":"内网IP|内网IP","browser":"Firefox-79.0","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:10:52"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjMyMjEzODAsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NjgyMSwibmJmIjoxNTk2NzYzMjIxfQ.hOCXNRIV8kpeULZ4mwQIOoq0Cux9Pmf_22mqDQ2v8EU","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.86","loginLocation":"内网IP|内网IP","browser":"Chrome-84.0.4147.105","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:20:21"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjI3MjA4NDEsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NjMyMCwibmJmIjoxNTk2NzYyNzIwfQ.cCB8bTnhCSJ3cM8JcWNBW3T5hrfhM9Bri8sJPewXp5w","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.76","loginLocation":"内网IP|内网IP","browser":"Chrome-84.0.4147.105","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:12:00"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjMzMTUxNTgsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NjkxNSwibmJmIjoxNTk2NzYzMzE1fQ.uoVeTAJs9QyR5ZUmbHXuNQkNVWtsK-k2ZQ9v8RljjTY","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.99","loginLocation":"内网IP|内网IP","browser":"Chrome-84.0.4147.105","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:21:55"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjI0NjQyMzIsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NjA2NCwibmJmIjoxNTk2NzYyNDY0fQ.GsHNJ0JXi87HN8wbtfopAeSi_Ck1PKQxllGVOTlXdEQ","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.121","loginLocation":"内网IP|内网IP","browser":"Chrome-76.0.3809.87","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:07:44"},{"tokenId":"bearer_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pblVpZCI6IjFmMDFjZDFkMmY0NzQ3NDNiMjQxZDc0MDA4YjEyMzMzIiwicm9sZSI6Im51bGzotoXnuqfnrqHnkIYiLCJjcmVhdFRpbWUiOjE1OTY3NjIzOTY2MTgsInN1YiI6ImFkbWluIiwiaXNzIjoibW9ndWJsb2ciLCJhdWQiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImV4cCI6MTU5Njc2NTk5NiwibmJmIjoxNTk2NzYyMzk2fQ.EmkxgkcYikimZYCJXGBJjMYh5iawA-fmMFikvitIKtM","adminUid":"1f01cd1d2f474743b241d74008b12333","userName":"admin","ipaddr":"192.168.71.80","loginLocation":"内网IP|内网IP","browser":"Chrome-83.0.4103.106","os":"Windows","roleName":"超级管理员","loginTime":"2020-08-07 09:06:36"}]}
    @RequestMapping("/getOnlineAdminList")
    public Result getOnlineAdminList(HttpServletRequest request){
        Map<String, Object> userInfo = TokenUtil.getUserInfo(request);
        String uid ;
        try {
            uid = (String) userInfo.get("uid");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,"获取失败");
        }
        List<Map<String,Object>>list = adminService.getOnlineAdminList(uid,request);
        return new Result(StatusCode.OK,list);
    }

    //8.重置用户密码  /admin/restPwd (管理员uid)  {"code":"success","data":"更新成功"}
    @RequestMapping("/restPwd")
    public  Result restPwd(String uid){

        try {
            int i= adminService.restPwd(uid);
            if (i>0){
                return new Result(StatusCode.OK,"更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(StatusCode.OK,"更新失败");
    }

    //9.更新管理员邮箱或手机号  POST /admin/updateEmail  (管理员uid,管理员新邮箱或新手机号//newInfo,验验码validCode)
   //{"code":"success","data":"更新成功"}
    @RequestMapping("/updateEmail")
    public Result updateEmail(@RequestBody Map map){

        String validCode = (String)map.get("validCode");
        String validate_code = (String)redisTemplate.boundValueOps("VALIDATE_CODE").get();
        //判断验证码是否正确
        if (validate_code != null && validate_code.equals(validCode)){
            int i= adminService.updateEmail(map);
            if (i>0){
                return new Result(StatusCode.OK,"更新成功");
            }else {
                return new Result(StatusCode.OK,"更新失败");
            }
        }
        return new Result(StatusCode.OK,"验证码错误");
    }

}
